package org.oslims.server.service.impl;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.oslims.domain.File;
import org.oslims.server.dao.FileDao;
import org.oslims.server.dao.hbm.HbmFileDao;
import org.oslims.server.dao.util.HibernateUtil;

public class FileDownloadService extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -910169528897744411L;

	private FileDao fileDao;

	public FileDownloadService() {
		fileDao = new HbmFileDao();
	}

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		Session session = HibernateUtil.getSession();

		fileDao.setSession(session);

		String fileId = request.getParameter("fileId");
		Long fileIdL;

		try {
			fileIdL = Long.parseLong(fileId);
		} catch (NumberFormatException e) {
			throw new ServletException("Input parameter is in a wrong format!");
		}

		File file = fileDao.findById(fileIdL, false);

		response.setContentType(file.getContentType());
		response.setHeader("Content-Disposition", "attachment; filename=" + file.getFileName());

		ServletOutputStream outputStream = response.getOutputStream();

		outputStream.write(file.getContent());

		outputStream.close();

		session.close();

	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// same logic
		this.doGet(request, response);
	}
}
